package com.demo.infrastructure.adapter;

import com.alibaba.fastjson.JSON;
import com.demo.domain.adapter.ICSDNPort;
import com.demo.domain.model.ArticleFunctionRequest;
import com.demo.domain.model.ArticleFunctionResponse;
import com.demo.infrastructure.gateway.ICSDNService;
import com.demo.infrastructure.gateway.dto.CSDNArticleRequest;
import com.demo.infrastructure.gateway.dto.CSDNArticleResponse;
import com.demo.type.properties.CSDNApiProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.io.IOException;

@Slf4j
@Component
public class CSDNPort implements ICSDNPort {
    @Resource
    private ICSDNService csdnService;
    @Resource
    private CSDNApiProperties properties;

    @Override
    public ArticleFunctionResponse writeArticle(ArticleFunctionRequest request) throws IOException {
        //request
        CSDNArticleRequest articleRequest = new CSDNArticleRequest();
        articleRequest.setTitle(request.getTitle());
        articleRequest.setMarkdowncontent(request.getMarkdowncontent());
        articleRequest.setContent(request.getContent());
        articleRequest.setTags(request.getTags());
        articleRequest.setCategories(properties.getCategories());
        articleRequest.setDescription(request.getDescription());
        //save
        Response<CSDNArticleResponse> response = csdnService.saveArticle(properties.getCookie(), articleRequest).execute();
        //log
        log.info("请求CSDN发帖：req:{}, res:{}", JSON.toJSONString(articleRequest), JSON.toJSONString(response));
        //result
        if (response.isSuccessful()) {
            CSDNArticleResponse articleResponse = response.body();
            if (articleResponse == null) return null;
            ArticleFunctionResponse articleFunctionResponse = new ArticleFunctionResponse();
            articleFunctionResponse.setCode(articleResponse.getCode());
            articleFunctionResponse.setMsg(articleResponse.getMsg());
            return articleFunctionResponse;
        }
        return null;
    }
}
